package org.cll.lagou.study.minicat.server;

import lombok.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * 描述信息:
 * 封装Request对象
 * @author CLL
 * @version 1.0
 * @date 2020/7/2 20:40
 */
@Getter
@Setter
@NoArgsConstructor
public class IRequest {

    private static final Logger logger = LoggerFactory.getLogger(IRequest.class);

    /**
     * HTTP/1.1
     */
    private String protocol;

    /**
     * GET
     */
    private String methodType;

    /**
     * /,/index.html
     */
    private String url;

    private String host;

    /**
     * 参数列表
     */
    private Map<String, String> params;

    /**
     * socket监听获取到的输入流
     */
    private InputStream inputStream;

    public IRequest(InputStream inputStream) throws IOException {
        this.inputStream = inputStream;
        init();
    }

    private void init() throws IOException{
        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }
        logger.debug("====== 当前输入流子节数量为 = {}", count);
        byte[] buffer = new byte[count];

        int read = inputStream.read(buffer);
        logger.debug("====== 读取到子节数组长度为 = {}", read);
        String inputStr = new String(buffer);
        logger.info("inputStream = {}", inputStr);

//        String[] split = inputStr.split("\\n");
        String firstLineStr = inputStr.split("\\n")[0];
        logger.info("firstLine = {}", firstLineStr);

        String[] headInfo = firstLineStr.split(" ");
        this.methodType = headInfo[0];
        logger.info("methodType = {}", methodType);
        this.url = headInfo[1];
        logger.info("url = {}", url);
        this.protocol = headInfo[2];
        logger.info("protocol = {}", protocol);

        String secondLineStr = inputStr.split("\\n")[1];
        String[] hostInfo = secondLineStr.split(":");
        for (String info : hostInfo) {
            logger.info("host info = {}", info.trim());
        }
        this.host = hostInfo[1].trim();
    }
}